package com.arcaneshift.servlet.util.parser.user;

import java.io.InputStream;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import com.arcaneshift.model.request.user.AddUserRequest;
import com.arcaneshift.model.response.user.AddUserResponse;
import com.arcaneshift.servlet.abstracts.XMLParserBase;
import com.arcaneshift.servlet.util.network.HTTPProtocol;
import com.common.model.abstracts.AbstractResponse;
import com.common.model.util.UserType;
import com.common.security.exceptions.HTTPException;
import com.common.security.exceptions.ParserException;
import com.common.security.exceptions.UserException;

public class AddUserXMLParser extends XMLParserBase {

	@Override
	public AddUserRequest parseRequest(InputStream stream) throws ParserException, HTTPException, UserException {
		AddUserRequest request = new AddUserRequest();
		
		Document document = createDocument(stream);
		
		Node actionNode = getActionNode(document);
		Node contentNode = getContentNode(document);
		
		insertAction(actionNode, request);
		Element element = getContent(contentNode);
		
		Element session = getElement(element, HTTPProtocol.SESSION);
		Element username = getElement(element, HTTPProtocol.USERNAME);
		Element password = getElement(element, HTTPProtocol.PASSWORD);
		Element usertype = getElement(element, HTTPProtocol.USER_TYPE);
		
		request.setSessionId(session.getAttribute(HTTPProtocol.ATTRIBUTE_VALUE));
		request.setUsername(username.getAttribute(HTTPProtocol.ATTRIBUTE_VALUE));
		request.setPassword(password.getAttribute(HTTPProtocol.ATTRIBUTE_VALUE));
		
		UserType type = UserType.parse(usertype.getAttribute(HTTPProtocol.ATTRIBUTE_VALUE));
		if (type == null) {
			throw new UserException(UserException.USER_TYPE_NOT_AVAILABLE);
		}
		request.setUserType(type);
				
		return request;
	}

	@Override
	public String parseResponse(AbstractResponse abstractResponse) throws ParserException {
		AddUserResponse response = null;
		if (abstractResponse instanceof AddUserResponse) {
			response = (AddUserResponse) abstractResponse;
		} else {
			throw new ParserException(ParserException.RESPONSE_MATCH_ERROR);
		}
		
		StringBuilder builder = new StringBuilder();
		
		builder.append(HTTPProtocol.RESPONSE_TAG);
		builder.append(HTTPProtocol.CLOSE_TAG);
		builder.append(HTTPProtocol.END_LINE);
		builder.append(getAction(response.getRequestAction()));
		builder.append(HTTPProtocol.CONTENT_TAG);
		builder.append(HTTPProtocol.END_LINE);
		builder.append(HTTPProtocol.CONTENT_END_TAG);
		builder.append(HTTPProtocol.END_LINE);
		builder.append(HTTPProtocol.RESPONSE_END_TAG);
		
		return builder.toString();
	}

}
